package com.yb7s.springboot.jdbc.dao.impl;

import com.yb7s.springboot.jdbc.dao.UserDao;
import com.yb7s.springboot.jdbc.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Date: 2019/3/3 12:49
 * @Auther: ybzhu
 * @Description：
 */
@Repository
public class UserDaoImpl implements UserDao {
    /**
     * 注入 jdbc
     */
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 新增
     * @param user
     * @return
     */
    @Override
    public int add(User user) {
        return jdbcTemplate.update("insert into user(name, money) values(?, ?)",user.getName(),user.getMoney());
    }

    /**
     * 修改
     * @param user
     * @return
     */
    @Override
    public int update(User user) {
        return jdbcTemplate.update("UPDATE  user SET NAME=? ,money=? WHERE id=?",user.getName(),user.getMoney(),user.getId());
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public int delete(int id) {
        return jdbcTemplate.update("DELETE from user where id=?",id);
    }

    /**
     * 查询一个
     * @param id
     * @return
     */
    @Override
    public User findUserById(int id) {
        List<User> list=jdbcTemplate.query("select * from user where id = ?", new Object[]{id}, new BeanPropertyRowMapper(User.class));
        if(list!=null && list.size()>0){
            User user = list.get(0);
            return user;
        }else{
            return null;
        }
    }

    /**
     * 查询列表
     * @return
     */
    @Override
    public List<User> findUserList() {
        List<User> list = jdbcTemplate.query("select * from user", new Object[]{}, new BeanPropertyRowMapper(User.class));
        if(list!=null && list.size()>0){
            return list;
        }else{
            return null;
        }
    }
}
